package com.xindaoapp.henghua.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.message.BasicHeader;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.library.utils.IRequest;
import com.library.utils.KeyValuePair;
import com.xindaoapp.henghua.R;
import com.xindaoapp.henghua.application.XinDaoApplication;
import com.xindaoapp.henghua.entry.PropertyGatherInfo;
import com.xindaoapp.henghua.entry.UnSubmitLabelInfo;
import com.xindaoapp.henghua.protocol.HttpManager;
import com.xindaoapp.henghua.utils.UpdateDataChanged.OnUpdateDataChangedListener;
import com.xindaoapp.henghua.utils.UploadFile;

public abstract class BaseActivity extends FragmentActivity {
	private LoadingDialog mLoadingDialog;
	/** 全部下载状态 */
	private boolean isDataLoading;

	private TextView tvNums;
	private TextView tvIcon;
	private Dialog dialog;
	private TextView submit;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		XinDaoApplication.get().getUpdateDataChanged().add(mOnUpdateDataChangedListener21);

		// 布局文件转换为view对象
		LayoutInflater inflaterDl = LayoutInflater.from(getSelf());
		LinearLayout layout = (LinearLayout) inflaterDl.inflate(R.layout.layout_submit_dialog, null);
		// 对话框
		dialog = new AlertDialog.Builder(getSelf()).setView(layout).create();

		tvNums = (TextView) layout.findViewById(R.id.tv_submit_nums);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		XinDaoApplication.get().getUpdateDataChanged().remove(mOnUpdateDataChangedListener21);
	}

	@Override
	protected void onStart() {
		super.onStart();
		initViews(getWindow().getDecorView());

		List<UnSubmitLabelInfo> unSubmitLabelInfos = XinDaoApplication.get().getDBHelper()
				.getUnSubmitLabels();

		int num = unSubmitLabelInfos != null ? unSubmitLabelInfos.size() : 0;

		if (0 == onSubmitButtonText()) {
			if (num != 0) {
				tvIcon.setVisibility(View.VISIBLE);
				tvIcon.setText("" + num);
			}
		}

	}

	private final OnUpdateDataChangedListener mOnUpdateDataChangedListener21 = new OnUpdateDataChangedListener() {

		@Override
		public void onUpdateDataChanged() {

			List<UnSubmitLabelInfo> unSubmitLabelInfos = XinDaoApplication.get().getDBHelper()
					.getUnSubmitLabels();

			int num = unSubmitLabelInfos != null ? unSubmitLabelInfos.size() : 0;

			if (0 == onSubmitButtonText()) {
				if (num != 0) {
					tvIcon.setVisibility(View.VISIBLE);
					tvIcon.setText("" + num);
				} else {
					tvIcon.setVisibility(View.GONE);
				}
			}
		}
	};

	private void initViews(View view) {
		View back = view.findViewById(R.id.back);
		if (null != back) {
			if (onShowBackButton()) {
				back.setVisibility(View.VISIBLE);
			} else {
				back.setVisibility(View.GONE);
			}
			back.setOnClickListener(mOnClickListener);
		}
		submit = (TextView) view.findViewById(R.id.local_submit);

		tvIcon = (TextView) view.findViewById(R.id.local_submit_num);

		if (null != submit) {
			if (onShowSubmitButton()) {
				submit.setVisibility(View.VISIBLE);
			} else {
				submit.setVisibility(View.GONE);
			}
			submit.setOnClickListener(mOnClickListener);

			if (0 != onSubmitButtonText()) {
				submit.setText(onSubmitButtonText());
			} else {
				submit.setText(R.string.local_submit);
			}
		}
		TextView title = ((TextView) view.findViewById(R.id.title));
		if (null != title) {
			title.setText(getTabTitle());
		}

		// 名字
		TextView name = (TextView) view.findViewById(R.id.name);
		if (null != name && null != XinDaoApplication.get().getUserInfo()) {
			name.setText(XinDaoApplication.get().getUserInfo().username);
		}

	}

	@Override
	public LayoutInflater getLayoutInflater() {
		return LayoutInflater.from(getBaseContext());
	}

	/**
	 * 获取Tab中间的名称
	 * 
	 * @return
	 */
	abstract String getTabTitle();

	/**
	 * 是否显示返回按钮
	 * 
	 * @return
	 */
	protected boolean onShowBackButton() {
		return true;
	}

	/**
	 * 是否显示一键提交按钮
	 * 
	 * @return
	 */
	protected boolean onShowSubmitButton() {
		return true;
	}

	protected int onSubmitButtonText() {
		return 0;
	}

	/**
	 * 是否显示数据初始化按钮
	 * 
	 * @return
	 */
	protected boolean onShowDownloadButton() {
		return true;
	}

	private final OnClickListener mOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.back:
				finish();
				break;
			case R.id.download:
				handleSubmitBtn();
				break;
			case R.id.local_submit:
				// 一键提交
				if (((TextView) getWindow().getDecorView().findViewById(R.id.local_submit)).getText().equals(
						getString(R.string.one_key_submit))) {
					uploadUnSubmitDatas();
				} else {
					Intent intent = new Intent(getSelf(), UnSubmitActivity.class);
					startActivity(intent);
				}
				break;
			default:
				break;
			}
		}
	};

	Handler h = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				CharSequence text = getString(R.string.submit_nums, successNums, total);
				tvNums.setText(text);
				break;

			default:
				break;
			}
		};
	};

	int total = 0;
	int successNums = 0;
	boolean canCancle = false;

	/**
	 * 上传未上传的数据
	 */
	private void uploadUnSubmitDatas() {
		final List<UnSubmitLabelInfo> unSubmitLabelInfos = XinDaoApplication.get().getDBHelper()
				.getUnSubmitLabels();

		if (unSubmitLabelInfos != null) {
			if (unSubmitLabelInfos.size() == 0) {
				return;
			}
		}

		total = unSubmitLabelInfos.size();
		successNums = 0;
		CharSequence text = getString(R.string.submit_nums, successNums, total);
		tvNums.setText(text);

		dialog.show();

		String contentJson = UploadFile.getJson(unSubmitLabelInfos);

		for (int i = 0; i < unSubmitLabelInfos.size(); i++) {
			String rawZipFolder = unSubmitLabelInfos.get(i).scanData.photoFilePath;
			String thumbZipFolder = unSubmitLabelInfos.get(i).scanData.breviaryFilePath;

			List<KeyValuePair<String, File>> list = new ArrayList<KeyValuePair<String, File>>();
			list.add(new KeyValuePair<String, File>("breviaryphotos", new File(rawZipFolder)));
			list.add(new KeyValuePair<String, File>("photos", new File(thumbZipFolder)));

			Header[] headers = new Header[1];

			Header header = new BasicHeader("content_json", contentJson);
			headers[0] = header;
			final int temp = i;
			UploadFile.uploadFile(list, headers, new IRequest<Boolean>() {

				@Override
				public void request(Boolean t) {
					if (t) {
						// 更新数据库中的状态
						XinDaoApplication.get().getDBHelper()
								.resetLabelState(unSubmitLabelInfos.get(temp).scanData.tag_code);
						XinDaoApplication.get().getUpdateDataChanged().notifyDataChanged();

						successNums++;
						h.sendEmptyMessage(0);
						if (temp == total - 1) {
							canCancle = true;
							dialog.dismiss();
						}
						if (successNums == unSubmitLabelInfos.size()) {
							// 重新加载数据
							handleSubmitBtn();
						}
					} else {
						if (temp == total - 1) {
							canCancle = true;
							dialog.dismiss();
						}
					}
				}
			}, XinDaoApplication.packageName, XinDaoApplication.versionName);
		}

	}

	/**
	 * 重新加载全部数据
	 */
	private void handleSubmitBtn() {
		mLoadingDialog = new LoadingDialog(getSelf(), R.style.Doading_Dialog);
		if (isHaveUnSubmitLabel()) {
			mLoadingDialog.setCanceledOnTouchOutside(true);
			mLoadingDialog.setImageView(R.drawable.failed);
			mLoadingDialog.show();
		} else {
			mLoadingDialog.setCanceledOnTouchOutside(false);
			mLoadingDialog.setImageView(R.drawable.down);
			mLoadingDialog.show();
//			startLoadData();
			Intent intent = new Intent(this,DeviceEngineerActivity.class);
			startActivity(intent);
			finish();
			
		}
	}

	/**
	 * 下载全部数据，下载完成的时候清空所有表
	 */
	private void startLoadData() {
		if (isDataLoading) {
			return;
		}
		isDataLoading = true;
		new HttpManager(XinDaoApplication.get().getUserInfo().project_id)
				.getPropertyGatherInfos(new IRequest<List<PropertyGatherInfo>>() {

					@Override
					public void request(List<PropertyGatherInfo> t) {
						isDataLoading = false;
						mLoadingDialog.dismiss();
						if (null != t) {
							// 清空所有表
							XinDaoApplication.get().getDBHelper().clearAllTable();
							// 保存数据到数据库
							for (PropertyGatherInfo info : t) {
								XinDaoApplication.get().getDBHelper().insertPropertyGatherInfo(info);
							}
							XinDaoApplication.get().getUpdateDataChanged().notifyDataChanged();
						} else {
							Toast.makeText(getBaseContext(), "加载失败", Toast.LENGTH_LONG).show();
						}
					}
				});
	}

	/**
	 * 是否有未提交的标签
	 */
	protected final boolean isHaveUnSubmitLabel() {
		if (XinDaoApplication.get().getDBHelper().getUnSubmitLabels().size() > 0) {
			return true;
		}
		return false;
	}

	public Context getSelf() {
		return this;
	}

	class LoadingDialog extends Dialog {
		private ImageView imageView;
		private int imageResource;

		public LoadingDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
			super(context, cancelable, cancelListener);
		}

		public LoadingDialog(Context context, int theme) {
			super(context, theme);
		}

		public LoadingDialog(Context context) {
			super(context);
		}

		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.dialog_downloading);
			setTheme(R.style.Doading_Dialog);
			imageView = (ImageView) findViewById(R.id.icon);
			imageView.setOnClickListener(mOnClickListener);
			imageView.setImageResource(imageResource);
		}

		private final View.OnClickListener mOnClickListener = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (imageResource == R.drawable.failed) {
					dismiss();
				}
			}
		};

		public void setImageView(int imageResource) {
			this.imageResource = imageResource;
			// imageView.setImageResource(imageResource);
		}
	}

	protected static final int DIALOG_LOADING = 1;// 数据加载
	protected static final int DIALOG_LOGIN = 2;// 登录
	protected static final int DIALOG_SUBMIT = 3;// 提交

	@Override
	@Deprecated
	protected Dialog onCreateDialog(int id) {
		ProgressDialog pd = new ProgressDialog(this);
		switch (id) {
		case DIALOG_LOADING:
			pd.setTitle(R.string.msg_hint);
			pd.setMessage(getString(R.string.loading_data));
			pd.setCancelable(false);
			return pd;
		case DIALOG_LOGIN:
			pd.setTitle(R.string.msg_hint);
			pd.setMessage(getString(R.string.loading_login));
			pd.setCancelable(false);
			return pd;
		case DIALOG_SUBMIT:
			pd.setTitle(R.string.msg_hint);
			pd.setMessage(getString(R.string.loading_submit));
			pd.setCancelable(false);
			return pd;
		}
		return null;
	}

	public TextView getTvTitle() {
		return ((TextView) getWindow().getDecorView().findViewById(R.id.title));
	}

}
